package com.jhws.util;

import java.io.*;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

public class ZipUtil {
	public static void zipFile(File inputFile, ZipOutputStream ouputStream) {
		try{
			if(inputFile.exists()){
				/**
				 * 如果是目录的话这里是不采取操作的， 至于目录的打包正在研究中
				 */
				if(inputFile.isFile()){
					FileInputStream IN = new FileInputStream(inputFile);
					BufferedInputStream bins = new BufferedInputStream(IN, 512);
					// org.apache.tools.zip.ZipEntry
					ZipEntry entry = new ZipEntry(inputFile.getName());
					ouputStream.putNextEntry(entry);
					// 向压缩文件中输出数据
					int nNumber;
					byte[] buffer = new byte[512];
					while ((nNumber = bins.read(buffer)) != -1){
						ouputStream.write(buffer, 0, nNumber);
					}
					// 关闭创建的流对象
					bins.close();
					IN.close();
				} else{
					try{
						File[] files = inputFile.listFiles();
						for(int i = 0; i < files.length; i++){
							zipFile(files[i], ouputStream);
						}
					} catch(Exception e){
						e.printStackTrace();
					}
				}
			}
		} catch(Exception e){
			e.printStackTrace();
		}
	}

	public static void zipFile(String name, InputStream IN, ZipOutputStream ouputStream) throws IOException {

		BufferedInputStream bins = new BufferedInputStream(IN, 512);
		// org.apache.tools.zip.ZipEntry
		ZipEntry entry = new ZipEntry(name);
		ouputStream.putNextEntry(entry);
		// 向压缩文件中输出数据
		int nNumber;
		byte[] buffer = new byte[512];
		while ((nNumber = bins.read(buffer)) != -1){
			ouputStream.write(buffer, 0, nNumber);
		}
		// 关闭创建的流对象
		bins.close();
	}
	
	public static void unZipFile(String fileName, String destFilePath) {
		int BUFFER = 1024*10;
		try {
			ZipFile zipFile = new ZipFile(fileName); 
			Enumeration emu = zipFile.entries();
			while (emu.hasMoreElements()) {
				ZipEntry entry = (ZipEntry) emu.nextElement();
				String filePath = destFilePath+ entry.getName().replace(':', '-');
				if (entry.isDirectory()) {				
					File dir = new File(filePath);
					if (!dir.exists()) {
						dir.mkdirs();
					}
					continue;
				}
				
				BufferedInputStream bis = new BufferedInputStream(
						zipFile.getInputStream(entry));
				
				System.out.println ( "decompress file :"+ filePath );
				File file = new File(filePath);
				File parent = file.getParentFile();
				if (parent != null && (!parent.exists())) {
					parent.mkdirs();
				}

				FileOutputStream fos = new FileOutputStream(file);
				BufferedOutputStream bos = new BufferedOutputStream(fos, BUFFER);
				byte[] buf = new byte[BUFFER];
				int len = 0;
				while ((len = bis.read(buf, 0, BUFFER)) != -1) {
					bos.write(buf, 0, len);
				}
				bos.flush();
				bos.close();
				bis.close();

			}
			zipFile.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
